package com.audaque.springboot.foshanupload.shardingsphere.config;


import com.audaque.springboot.foshanupload.shardingsphere.utils.ShardingUtil;
import io.shardingsphere.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.api.algorithm.sharding.standard.RangeShardingAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ShardingRangeTableStrategy implements RangeShardingAlgorithm<Date> {
    public ShardingRangeTableStrategy() {
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> shardingValue) {
        String startName = ShardingUtil.getTableName(shardingValue.getLogicTableName(), shardingValue.getValueRange().lowerEndpoint());
        String endName = ShardingUtil.getTableName(shardingValue.getLogicTableName(), shardingValue.getValueRange().upperEndpoint());

        List<String> tableNames = availableTargetNames.stream().filter(t -> {
            String[] iArr = t.split("_");
            String[] sArr = startName.split("_");
            String[] eArr = endName.split("_");
            Integer i = Integer.valueOf(iArr[iArr.length - 1]);
            Integer s = Integer.valueOf(sArr[sArr.length - 1]);
            Integer e = Integer.valueOf(eArr[eArr.length - 1]);
            return i - s >= 0 && i - e <= 0;
        }).collect(Collectors.toList());
        return tableNames;
    }
}
